package mo.leetcode_top;

import java.util.Stack;

public class L227 {

    public int calculate(String s) {
        int res = 0;
        int num = 0;
        int n = s.length();
        char op = '+';
        Stack<Integer> nums = new Stack<>();
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) >= '0') {
                num = num * 10 + (s.charAt(i) - '0');
            }
            if ((s.charAt(i) < '0' && s.charAt(i) != ' ') || i == n-1) {
                if (op == '+') {
                    nums.push(num);
                } else if (op == '-') {
                    nums.push(-num);
                } else if (op == '*' || op == '/') {
                    int first = nums.pop();
                    int tmp = (op == '*') ? first * num : first / num;
                    nums.push(tmp);
                }
                op = s.charAt(i);
                num = 0;
            }
        }

        while (!nums.isEmpty()) {
            res += nums.pop();
        }

        return res;
    }


    public static void main(String[] args) {
        L227 test = new L227();
        System.out.println(test.calculate("3+5 / 2"));
    }

}
